from flask import Blueprint, request, jsonify
from db import get_db

user = Blueprint('user', __name__)

@user.route('/login', methods=['POST'])
def login():
    uid = request.json['uid']
    upassword = request.json['upassword']
    
    db = get_db()
    with db.cursor() as cursor:
        cursor.execute(f"SELECT * FROM USER WHERE uid = '{uid}' AND upassword = '{upassword}'")
        userinfo = cursor.fetchall()
    
    db.close()    
    returninfo = userinfo[0] if len(userinfo) == 1 else None
    return jsonify({"result": len(userinfo) == 1, "userinfo": returninfo})
    
@user.route('/register', methods=['POST'])
def register():
    uname = request.json['uname']
    upassword = request.json['upassword']
    
    db = get_db()
    sql = f"INSERT INTO USER (uname, upassword) VALUES ('{uname}', '{upassword}')"
    
    cursor = db.cursor()
    try:
        cursor.execute(sql)
        db.commit()
    except Exception as e:
        db.rollback()
        db.close()
        return jsonify({"result": False, "error": str(e)})
    
    with db.cursor() as cursor:
        cursor.execute(f"SELECT * FROM USER")
        userinfo = cursor.fetchall()[-1]
    uid = userinfo['uid']
    
    db.close()
    
    return jsonify({"result": True, "uid": uid})
    
@user.route('/', methods=['GET'])
def get_all_users():
    db = get_db()
    try:
        with db.cursor() as cursor:
            cursor.execute("SELECT uid, uname FROM USER")
            users = cursor.fetchall()
        return jsonify({"result": True, "users": users})
    except Exception as e:
        return jsonify({"result": False, "error": str(e)})
    finally:
        db.close()